package com.stanwind.controller.game;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.stanwind.api.Log;
import com.stanwind.api.RedisUtils;
import com.stanwind.constant.ServerSetting;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Set;

/**
 * Created by StanWind on 2017/2/17.
 */
@Controller
public class MatchRoomController {
    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private Log log;

    @RequestMapping("matchRoom")
    public
    @ResponseBody
    Object matchRoom() {
        Jedis jedis = redisUtils.getJedisObject();
        Set<String> servers = jedis.keys(ServerSetting.SERVER_NAME_PRE + "?");
        Random random = new Random();

        List<String> s = new ArrayList<String>();
        s.addAll(servers);
        int id = random.nextInt()%s.size();
        //FIXME 随机均衡有问题 数组越界  ArrayIndexOutOfBoundsException
        String serverName = s.get(0);
        log.getLogger().debug("id "+id+"------------>size "+s.size());
        String jsonStr = jedis.get(serverName);
        JSONObject jsonObj =JSONObject.parseObject(jsonStr);
        jsonObj.put("name",serverName);
        redisUtils.recycleJedisOjbect(jedis);
        return jsonObj;
    }
}
